import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 800
HEIGHT = 600
CAR_WIDTH = 50
CAR_HEIGHT = 100
OBSTACLE_WIDTH = 50
OBSTACLE_HEIGHT = 50
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("模拟赛车手游戏")

# 赛车类
class Car:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = 5

    def move_left(self):
        if self.x > 0:
            self.x -= self.speed

    def move_right(self):
        if self.x < WIDTH - CAR_WIDTH:
            self.x += self.speed

    def draw(self):
        pygame.draw.rect(screen, GREEN, (self.x, self.y, CAR_WIDTH, CAR_HEIGHT))

# 障碍物类
class Obstacle:
    def __init__(self, x):
        self.x = x
        self.y = -OBSTACLE_HEIGHT
        self.speed = 3

    def move_down(self):
        self.y += self.speed

    def draw(self):
        pygame.draw.rect(screen, RED, (self.x, self.y, OBSTACLE_WIDTH, OBSTACLE_HEIGHT))

    def is_off_screen(self):
        return self.y > HEIGHT

    def collide_with(self, car):
        return (
            self.x < car.x + CAR_WIDTH
            and self.x + OBSTACLE_WIDTH > car.x
            and self.y < car.y + CAR_HEIGHT
            and self.y + OBSTACLE_HEIGHT > car.y
        )

# 创建赛车
car = Car(WIDTH // 2 - CAR_WIDTH // 2, HEIGHT - CAR_HEIGHT - 10)
obstacles = []

# 时钟对象，用于控制帧率
clock = pygame.time.Clock()

# 游戏主循环
running = True
while running:
    screen.fill(WHITE)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                car.move_left()
            elif event.key == pygame.K_RIGHT:
                car.move_right()

    # 随机生成障碍物
    if random.randint(1, 100) < 3:
        obstacle_x = random.randint(0, WIDTH - OBSTACLE_WIDTH)
        obstacles.append(Obstacle(obstacle_x))

    # 移动和绘制障碍物
    new_obstacles = []
    for obstacle in obstacles:
        obstacle.move_down()
        if obstacle.is_off_screen():
            continue
        if obstacle.collide_with(car):
            print("碰撞！游戏结束。")
            running = False
        obstacle.draw()
        new_obstacles.append(obstacle)
    obstacles = new_obstacles

    # 绘制赛车
    car.draw()

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()